import type { BaseEntity } from "@/entity/BaseEntity";
import type { Page } from "@/entity/Page";
import type { ResponseResult } from "@/entity/ResponseResult";
import type { AxiosResponse } from "axios";
import httpClient from "./http-client";

export abstract class BaseEntityService<T extends BaseEntity> {
    abstract baseUrl: string;

    async page(no: number = 1, size: number = 10, searchObj?: T): Promise<Page<T>> {
        // 前端从1开始计数，后端从0开始计数
        no = no - 1;
        return httpClient.post(`${this.baseUrl}/page?no=${no}&size=${size}`, {
            ...searchObj,
        }).then((res: AxiosResponse<ResponseResult<Page<T>>>) => {
            if (res.data.data) {
                const page = res.data.data;
                // 前端从1开始计数，后端从0开始计数
                page.number = page.number + 1;
                return Promise.resolve(page);
            } else {
                throw "no data";
            }
        });
    }

    async search(text: string | null = "", page: number = 1, size: number = 10): Promise<Page<T>> {
        // 前端从1开始计数，后端从0开始计数
        page = page - 1;
        return httpClient.get(`${this.baseUrl}/search?text=${text}&page=${page}&size=${size}`).then((res: AxiosResponse<ResponseResult<Page<T>>>) => {
            if (res.data.data) {
                const page = res.data.data;
                // 前端从1开始计数，后端从0开始计数
                page.number = page.number + 1;
                return Promise.resolve(page);
            } else {
                throw "no data";
            }
        });
    }

    async retrieve(id: number): Promise<T> {
        return httpClient.get(`${this.baseUrl}/retrieve/${id}`).then((res) => {
            return Promise.resolve(res.data.data);
        });
    }

    async insert(e: T): Promise<number> {
        const body = e;
        return httpClient.post(`${this.baseUrl}/create`, body).then((res) => {
            return Promise.resolve(res.data.data);
        });
    }

    async update(e: T): Promise<null> {
        const body = e;
        return httpClient.put(`${this.baseUrl}/update`, body).then((res) => {
            return Promise.resolve(res.data.data);
        });
    }

    async remove(ids: number[] = []): Promise<null> {
        return httpClient.delete(`${this.baseUrl}/remove?ids=${ids.join(",")}`).then((res) => {
            return Promise.resolve(res.data.data);
        });
    }
}

export default BaseEntityService;